package com.example.edf_jimmy;
import com.example.edf_jimmy.Client;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.net.ParseException;
import android.os.Environment;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;

public class Modele {
	private String DB4OFILENAME; 
	private ObjectContainer db;
	private File appDir;
	
	public Modele(){
		mkdir();
		open();
		chargeDb();
		db.close();
	}
	
	public void open(){
		
		DB4OFILENAME=Environment.getExternalStorageDirectory()+"/baseDB4O"+"/BaseEDF_Jimmy.db4o";
		db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(), DB4OFILENAME);
		
	}
	public void close(){
		db.close();
	}
	
	public void mkdir(){
		appDir = new File(Environment.getExternalStorageDirectory()+"/baseDB4O");
		if(!appDir.exists() && !appDir.isDirectory()) 
		    {
		        appDir.mkdirs();
		    }
	}
	
	public ArrayList<Client> listClient(){
		
		ObjectSet<Client> result = db.queryByExample(Client.class);
		ArrayList<Client> lesClients = new ArrayList<Client>();
		
		while (result.hasNext()) {
			lesClients.add((Client)result.next());
		}
		
		return lesClients;
	}
	
	public Client trouveClient(String id){
		open();
		Client vretour = new Client();
		vretour.setIdentifiant(id);
		ObjectSet<Client> result = db.queryByExample(vretour);
		
		while (result.hasNext()) {
			vretour = (Client)result.next();
		}
		db.close();
		return vretour;
	}
	
	public void saveClient(Client unClient){
		Client vretour = trouveClient(unClient.getIdentifiant());
		if (vretour.getIdentifiant() != null){
			db.store(vretour);
		}
		else {
			db.store(unClient);
		}
	}
	
	public void chargeDb(){
		ArrayList<Client> lesClients = listClient();
		Client vcli = new Client();
	
		if(lesClients.size() == 0){
						
				try {
					vcli = new Client("1001", "Dupont", "paul",
							"10 rue Anne Frank", "49000", "angers",
							"0624553212", "19950055123", 1456.24,
							new SimpleDateFormat("dd/MM/yyyy").parse("15/03/2012"));
					
				} catch (java.text.ParseException e) {
					e.printStackTrace();
				}
				
				db.store(vcli);
				
			
		}
	}
}